'''
孝欣保恶性肿瘤医疗险特惠版
'''
import sys

sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper


class Spider(object):
    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "孝欣保恶性肿瘤医疗险特惠版"

    # 生产产品价格
    def genProductInfo(self):

        plan = {

            "planA":
                {

                    # 年龄段
                    "year": [str(i) for i in range(45, 81)],
                    # 社保
                    "socialSec": ["Y", "N"],
                    # 保障计划
                    "plan": ["基础款(2万年免赔)"],
                    # 计划代码
                    "planCode": ["PACK190350368007"],
                    # 附加保险(质子重离子医疗保险责任)
                    "ext_medical": ["0", "1"],
                    # 附加保险(中老年人特定疾病保险责任)
                    "ext_special": ["0", "1"]

                },
            "planB":
                {

                    # 年龄段
                    "year": [str(i) for i in range(45, 81)],
                    # 社保
                    "socialSec": ["Y", "N"],
                    # 保障计划
                    "plan": ["基础款(1万年免赔)"],
                    # 计划代码
                    "planCode": ["PACK190338568006"],
                    # 附加保险(质子重离子医疗保险责任)
                    "ext_medical": ["0", "1"],
                    # 附加保险(中老年人特定疾病保险责任)
                    "ext_special": ["0", "1"]

                },
            "planC":
                {

                    # 年龄段
                    "year": [str(i) for i in range(45, 81)],
                    # 社保
                    "socialSec": ["Y", "N"],
                    # 保障计划
                    "plan": ["基础款(0免赔)"],
                    # 计划代码
                    "planCode": ["PACK190333568005"],
                    # 附加保险(质子重离子医疗保险责任)
                    "ext_medical": ["0", "1"],
                    # 附加保险(中老年人特定疾病保险责任)
                    "ext_special": ["0", "1"]

                }

        }

        for k in plan:

            for v in product(plan[k]["year"], plan[k]["socialSec"], plan[k]["plan"], plan[k]["planCode"],
                             plan[k]["ext_medical"], plan[k]["ext_special"]):
                # 写入数据库

                expire = "1年"
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(

                    v[0], v[1], v[2], v[3], expire, v[4], v[5]

                ))
                self.mysql._conn.commit()
                print(

                    domain[self.name]["insert_sql"].format(

                        v[0], v[1], v[2], v[3], expire, v[4], v[5]

                    )

                )

    # 执行爬虫
    def requestJson(self, dt=None):

        # dt = {
        #
        #     "year":"48",
        #     "socialSec":"N",
        #     "planCode":"PACK190350368007",
        #     "ext_medical":"0",
        #     "ext_special":"1"
        # }

        payload = self.RequestParams( dt )

        print( payload )

        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=json.dumps(payload))

        print( r.text )

        if r.status_code == 200 and r.json()["status"] == 200:

            price = Helper.decimalParse(r.json()["data"])

            data = {

                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )


        else:

            # 任务执行失败
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            self.mysql.updateTask(data)

            print("产品价格更新失败:", dt["id"])

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)

    # 获取计划代码
    def RequestParams(self, dt=None, url="https://p.zhongan.com/api/productmarketpc/product/v1/getPremiumFactors"):

        payloads = {"bizNo": "INST190988426092", "productCode": "PRD190527921014", "packageCode": dt["planCode"],
                   "optionProjectIdList": [1008005, 1008006],
                   "premiumFactorList": [{"productPremiumFactorId": 1016001, "value": "1", "unit": "年"},
                                         {"productPremiumFactorId": 1016002,
                                          "value": "{year}-02-02".format(year=str(2019 - int(dt["year"]))),
                                          "unit": ""},
                                         {"productPremiumFactorId": 1016003,
                                          "value": "有" if dt["socialSec"] == "Y" else "无", "unit": ""}],
                   "marketProductCode": "PRD190341916002"}



        headers = headers_raw_to_dict(

            b'''
            Accept: application/json, text/plain, */*
            Accept-Encoding: gzip, deflate, br
            Accept-Language: zh-CN,zh;q=0.9
            Connection: keep-alive
            Content-Length: 156
            Content-Type: application/json;charset=UTF-8
            Cookie: __utrace=db7ab2bbc2bfbb3e2ec5bada465799d0; _ga=GA1.2.1459978551.1576026467; ISEE_DEVICE_ID_V2=d99ec298ce025cb3bacbebb97b1a76a1; _i_m_t_uid=_i_m_t_uid1576545758883_481; _i_m_v_id=_i_m_v_id1576545758885_545; Hm_lvt_ecc6d381dd1b2d77f324681c7a9d76d5=1576026468,1576739746; Hm_lvt_d792eb5ed311e5605c562e0f39e100cb=1576026467,1576739746; Hm_lvt_ae858e8ef214d7a3acf034b9f6704dea=1576656910,1576716145,1577932345,1578449261; __visits_id=9ebe117b27cc3017f7fde71198edf6ed; bizOrigin=zx2019pc; Hm_lvt_acea3d0365fa5bc7ccbd0a6bca32db48=1576656910,1576716145,1577932345,1578449261; Hm_lpvt_ae858e8ef214d7a3acf034b9f6704dea=1578455635; Hm_lpvt_acea3d0365fa5bc7ccbd0a6bca32db48=1578455635; ISEE_BIZ=011a0c3qLTLnIyvOvtoIJQOZQH3; ISEE_COUNT=426
            Host: p.zhongan.com
            Origin: https://p.zhongan.com
            Referer: https://p.zhongan.com/market/pc/product?productCode=PRD190527921014&bizOrigin=zx2019pc&bizType=1&bizNo=INST190988426092
            Sec-Fetch-Mode: cors
            Sec-Fetch-Site: same-origin
            User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36
            X-Requested-With: XMLHttpRequest
            '''
        )

        if dt["planCode"] == "PACK190350368007":

            projects = []

            data = {

                "ext_medical": dt["ext_medical"],
                "ext_special": dt["ext_special"]
            }

            code = {

                "ext_medical": 1008005,
                "ext_special": 1008006

            }

            for k, v in data.items():

                if v != "0":

                    projects.append(code[k])

                else:

                    pass

            payload = {"packageCode": dt["planCode"], "productPackageId": 51374706, "bizNo": "INST190988426092",
                       "merchantLoginName": "", "packageOptionProjectIds": ""}

            payload["packageOptionProjectIds"] = projects


            r = requests.post(url=url, headers=headers, data=json.dumps(payload))

            if r.status_code == 200 and r.json()["status"] == 200:

                factoryIds = self.ParseFactoryId(r.json())

                payloads["optionProjectIdList"] = projects
                payloads["premiumFactorList"][0]["productPremiumFactorId"] = factoryIds[0]
                payloads["premiumFactorList"][1]["productPremiumFactorId"] = factoryIds[1]
                payloads["premiumFactorList"][2]["productPremiumFactorId"] = factoryIds[2]

                return payloads


        elif dt["planCode"] == "PACK190338568006":

            projects = []

            data = {

                "ext_medical": dt["ext_medical"],
                "ext_special": dt["ext_special"]
            }

            code = {

                "ext_medical": 1008003,
                "ext_special": 1008004

            }

            for k, v in data.items():

                if v != "0":

                    projects.append(code[k])

                else:

                    pass

            payload = {"packageCode": dt["planCode"], "productPackageId": 51374704, "bizNo": "INST190988426092",
                       "merchantLoginName": "", "packageOptionProjectIds": ""}

            payload["packageOptionProjectIds"] = projects


            r = requests.post(url=url, headers=headers, data=json.dumps(payload))


            if r.status_code == 200 and r.json()["status"] == 200:

                factoryIds = self.ParseFactoryId(r.json())

                payloads["optionProjectIdList"] = projects
                payloads["premiumFactorList"][0]["productPremiumFactorId"] = factoryIds[0]
                payloads["premiumFactorList"][1]["productPremiumFactorId"] = factoryIds[1]
                payloads["premiumFactorList"][2]["productPremiumFactorId"] = factoryIds[2]

                return payloads


        else:

            projects = []

            data = {

                "ext_medical": dt["ext_medical"],
                "ext_special": dt["ext_special"]
            }

            code = {

                "ext_medical": 1008001,
                "ext_special": 1008002

            }

            for k, v in data.items():

                if v != "0":

                    projects.append(code[k])

                else:

                    pass

            payload = {"packageCode": dt["planCode"], "productPackageId": 51374705, "bizNo": "INST190988426092",
                       "merchantLoginName": "", "packageOptionProjectIds": ""}

            payload["packageOptionProjectIds"] = projects


            r = requests.post(url=url, headers=headers, data=json.dumps(payload))

            if r.status_code == 200 and r.json()["status"] == 200:

                factoryIds = self.ParseFactoryId(r.json())

                payloads["optionProjectIdList"] = projects
                payloads["premiumFactorList"][0]["productPremiumFactorId"] = factoryIds[0]
                payloads["premiumFactorList"][1]["productPremiumFactorId"] = factoryIds[1]
                payloads["premiumFactorList"][2]["productPremiumFactorId"] = factoryIds[2]

                return payloads

    # 获取factoryId
    def ParseFactoryId(self, data):

        factoryIds = []

        for v in data["data"]:

            factoryIds.append(v["premiumFactorId"])


        return factoryIds
